package storage.record;

import storage.file.*;
import metadata.schema.Schema;
import utils.Lib;
import error.EBFileException;

public class Record {

	private BlockID block;
	private int offset;	// offset inside a block
	private int rid;
	
	/**
	 * header contains (in byte):
	 * 0-3		: pointer to record schema
	 * 4-7		: length
	 * 8-11		: timestamp
	 */
	private static final int RECORD_HEADER_LENGTH = 12;
	private static final int SCHEMA_OFFSET = 0;
	private static final int LENGTH_OFFSET = 4;
	private static final int TIMESTAMP_OFFSET = 8;
	private byte[] header;
	private Schema schema;
	private int length;
	private int timestamp;
	private byte[] content;

	/**
	 * Construct a record, specifying its rid and block info <br>
	 * <i>Should only be invoked by HeapFile.getRecord(rid).</i>
	 * @param rid, block, offset
	 */
	public Record(int rid, BlockID block, int offset) {
		this.rid = rid;
		this.block = block;
		this.offset = offset;
		
		load();
	}
	
	private void load() {
		load(block, offset);
	}
	
	public void load(BlockID block, int offset) {
		try {
			// header
			header = new byte[RECORD_HEADER_LENGTH];
			FileManagerFactory.getFileManager().read(block, offset, 0, RECORD_HEADER_LENGTH, header);
			
			length = Lib.bytesToInt(header, LENGTH_OFFSET);
			timestamp = Lib.bytesToInt(header, TIMESTAMP_OFFSET);
			
			// content
			content = new byte[length];
			FileManagerFactory.getFileManager().read(block, offset, 0, length, content);
		} catch (EBFileException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
/*	public byte[] getField(String fieldName) {
		// TODO: fill this method
		return null;
	}*/
	
//	public byte[] getField(int fieldNumber) {
//		
//	}
	
}